<script setup lang="ts">
  import { useRecordingStore } from '@renderer/store/modules/recording.store'
  import { onUnmounted, ref } from 'vue'
  import { useI18n } from 'vue-i18n'

  const recordingStore = useRecordingStore()
  const { t } = useI18n()
  const isSelecting = ref(false)
  const isOverlayVisible = ref(false)
  const hasSelection = ref(false)
  const startPoint = ref({ x: 0, y: 0 })
  const endPoint = ref({ x: 0, y: 0 })
  const overlay = ref<HTMLDivElement | null>(null)
  const selection = ref<HTMLDivElement | null>(null)

  defineExpose({
    showOverlay
  })

  // 显示遮罩层
  function showOverlay() {
    isOverlayVisible.value = true
    hasSelection.value = false
    if (overlay.value) {
      overlay.value.style.display = 'block'
    }

    // 通知父组件遮罩层已显示，应该关闭菜单
    emit('overlay-shown')
  }

  // 开始选择区域
  function startSelection(e: MouseEvent) {
    // 如果点击的是按钮或指引提示，不进行区域选择
    if (
      (e.target as HTMLElement).closest('.region-cancel-btn') ||
      (e.target as HTMLElement).closest('.region-guide') ||
      (e.target as HTMLElement).closest('.region-confirm-btn') ||
      (e.target as HTMLElement).closest('.region-reselect-btn')
    ) {
      return
    }

    // 清除之前的选择
    hasSelection.value = false
    isSelecting.value = true
    startPoint.value = { x: e.clientX, y: e.clientY }
    endPoint.value = { x: e.clientX, y: e.clientY }

    // 监听鼠标移动和鼠标释放事件
    document.addEventListener('mousemove', updateSelection)
    document.addEventListener('mouseup', endSelection)
  }

  // 更新选择区域
  function updateSelection(e: MouseEvent) {
    if (!isSelecting.value) return

    endPoint.value = { x: e.clientX, y: e.clientY }
    updateSelectionBox()
  }

  // 更新选择框的位置和大小
  function updateSelectionBox() {
    if (!selection.value) return

    const left = Math.min(startPoint.value.x, endPoint.value.x)
    const top = Math.min(startPoint.value.y, endPoint.value.y)
    const width = Math.abs(endPoint.value.x - startPoint.value.x)
    const height = Math.abs(endPoint.value.y - startPoint.value.y)

    selection.value.style.left = `${left}px`
    selection.value.style.top = `${top}px`
    selection.value.style.width = `${width}px`
    selection.value.style.height = `${height}px`
    selection.value.style.display = 'block'
  }

  // 结束选择区域
  function endSelection() {
    if (!isSelecting.value) return

    isSelecting.value = false

    // 移除事件监听
    document.removeEventListener('mousemove', updateSelection)
    document.removeEventListener('mouseup', endSelection)

    // 检查选择区域是否有效
    const selectionWidth = Math.abs(endPoint.value.x - startPoint.value.x)
    const selectionHeight = Math.abs(endPoint.value.y - startPoint.value.y)

    if (selectionWidth > 10 && selectionHeight > 10) {
      // 标记已有选择
      hasSelection.value = true
    } else {
      // 如果选择区域太小，重置选择
      if (selection.value) {
        selection.value.style.display = 'none'
      }
    }
  }

  // 获取设备像素比率
  function getDevicePixelRatio() {
    return window.devicePixelRatio || 1
  }

  // 确认选择区域
  function confirmSelection() {
    const left = Math.min(startPoint.value.x, endPoint.value.x)
    const top = Math.min(startPoint.value.y, endPoint.value.y)
    const width = Math.abs(endPoint.value.x - startPoint.value.x)
    const height = Math.abs(endPoint.value.y - startPoint.value.y)

    // 考虑设备像素比例
    const pixelRatio = getDevicePixelRatio()
    console.log('设备像素比例:', pixelRatio)

    // 保存选择区域信息，包括设备像素比
    recordingStore.updateSettings({
      captureType: 'region',
      captureRegion: {
        enabled: true,
        x: left,
        y: top,
        width,
        height,
        devicePixelRatio: pixelRatio
      }
    })

    // 隐藏选择区域
    hideOverlay()

    // 通知父组件选择完成
    emit('selection-complete')
  }

  // 重新选择区域
  function reselectArea() {
    hasSelection.value = false
    if (selection.value) {
      selection.value.style.display = 'none'
    }
  }

  // 隐藏遮罩层和选择框
  function hideOverlay() {
    isOverlayVisible.value = false
    hasSelection.value = false
    if (overlay.value) {
      overlay.value.style.display = 'none'
    }

    if (selection.value) {
      selection.value.style.display = 'none'
    }
  }

  // 取消选择
  function cancelSelection() {
    isSelecting.value = false
    document.removeEventListener('mousemove', updateSelection)
    document.removeEventListener('mouseup', endSelection)

    hideOverlay()

    recordingStore.updateSettings({
      captureType: 'window',
      captureRegion: {
        ...recordingStore.settings.captureRegion,
        enabled: false
      }
    })

    emit('selection-cancel')
  }

  // 定义事件
  const emit = defineEmits<{
    (e: 'selection-complete'): void
    (e: 'selection-cancel'): void
    (e: 'overlay-shown'): void
  }>()

  // 组件卸载时清理事件监听
  onUnmounted(() => {
    document.removeEventListener('mousemove', updateSelection)
    document.removeEventListener('mouseup', endSelection)
  })
</script>

<template>
  <!-- 区域选择遮罩层 -->
  <teleport to="body">
    <div
      ref="overlay"
      class="region-select-overlay"
      style="display: none"
      @mousedown="startSelection"
    >
      <!-- 选择区域框 -->
      <div ref="selection" class="region-select-box" style="display: none">
        <div class="region-size-info">
          {{ Math.abs(endPoint.x - startPoint.x) }} x {{ Math.abs(endPoint.y - startPoint.y) }}
        </div>

        <!-- 确认/重选按钮组 -->
        <div v-if="hasSelection" class="region-action-buttons">
          <button class="region-confirm-btn" @click="confirmSelection">
            <i class="i-mynaui-check mr-1"></i>
            {{ t('recording-bar.region-select.confirm') || '确认' }}
          </button>
          <button class="region-reselect-btn" @click="reselectArea">
            <i class="i-mynaui-refresh mr-1"></i>
            {{ t('recording-bar.region-select.reselect') || '重选' }}
          </button>
        </div>
      </div>

      <!-- 指引提示 -->
      <div class="region-guide" v-if="!isSelecting && !hasSelection">
        <div class="region-guide-icon">
          <i class="i-mynaui-mouse text-3xl"></i>
        </div>
        <div class="region-guide-text">
          {{ t('recording-bar.region-select.guide') || '点击并拖动鼠标选择录制区域' }}
        </div>
      </div>

      <!-- 取消按钮 -->
      <button class="region-cancel-btn" @click="cancelSelection">
        {{ t('recording-bar.region-select.cancel') || '取消' }}
      </button>
    </div>
  </teleport>
</template>

<style lang="scss" scoped>
  .region-select-btn {
    @apply flex items-center justify-center text-white bg-indigo-600 hover:bg-indigo-700 py-1 px-3 rounded-md text-sm;
  }

  .region-select-overlay {
    @apply fixed inset-0 bg-black/30 z-50 cursor-crosshair;
  }

  .region-select-box {
    @apply absolute border-2 border-indigo-500 bg-indigo-100/20 z-[51];

    .region-size-info {
      @apply absolute -top-6 left-0 bg-indigo-600 text-white px-2 py-0.5 text-xs rounded-t-md;
    }

    .region-action-buttons {
      @apply absolute -bottom-10 left-0 flex space-x-2;

      .region-confirm-btn {
        @apply bg-green-600 hover:bg-green-700 text-white py-1 px-3 rounded-md text-xs flex items-center;
      }

      .region-reselect-btn {
        @apply bg-blue-600 hover:bg-blue-700 text-white py-1 px-3 rounded-md text-xs flex items-center;
      }
    }
  }

  .region-guide {
    @apply fixed top-1/2 left-1/2 -translate-x-1/2 -translate-y-1/2 flex flex-col items-center justify-center text-white p-4 rounded-lg bg-black/50 z-[52];

    .region-guide-icon {
      @apply mb-2;
    }

    .region-guide-text {
      @apply text-sm font-medium;
    }
  }

  .region-cancel-btn {
    @apply fixed top-4 right-4 bg-red-600 hover:bg-red-700 text-white py-1 px-3 rounded-md text-sm;
  }
</style>
